<?php
// +----------------------------------------------------------------------
// | sfadmin - Suifeng Administration
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2020 http://suifeng.tech All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: suifeng <1787585212@qq.com>
// +----------------------------------------------------------------------

namespace suifeng\builder\form\validator;

use suifeng\builder\form\Validator;

class Length extends Validator
{
    /*
     * 最大长度。
     */
    public $max;

    /*
     * 最大长度。
     */
    public $min;

    /**
     * 默认信息。
     *
     * @var array
     */
    protected $default_messages = [
        '{control.label} 长度必须在{min}和{max}之间。',
        '{control.label} 长度必须大于或等于{min}。',
        '{control.label} 长度必须小于或等于{max}。',
    ];

    /**
     * 验证方法。
     */
    protected function _validate_core()
    {
        $value = $this->_get_control_value();

        if (is_string($value)) {
            if ($this->min && $this->max && (strlen($value) < $this->min || strlen($value) > $this->max)) {
                $message = $this->message ? $this->message : $this->default_messages[0];
                $this->errors[] = $this->_format_message($message);
            } else if ($this->min && strlen($value) < $this->min) {
                $message = $this->message ? $this->message : $this->default_messages[1];
                $this->errors[] = $this->_format_message($message);
            } else if ($this->max && strlen($value) > $this->max) {
                $message = $this->message ? $this->message : $this->default_messages[2];
                $this->errors[] = $this->_format_message($message);
            }
        }
    }
}
